# 编辑函数都放在这
# from sqlalchemy import func

from flask import session
from .models import *
import uuid
import os


# 查询当前项目图片，返回列表
def ger_pic_list(picture_object1, picture_ob_type1):
    pic_now = Picture.query.filter_by(picture_object=picture_object1,picture_ob_type=picture_ob_type1).all()
    if pic_now is None:
        return []
    pic_list = []
    for pic_now1 in pic_now:
        pic_list.append(pic_now1.picture_address)
    return pic_list


def get_page_data(data_list, page, page_num):
    page_size = page_num  # 每页元素数量
    start_index = (page ) * page_size
    end_index = start_index + page_size
    # 确保不会超出列表范围
    end_index = min(end_index, len(data_list))
    print(start_index, end_index)

    # 返回分页数据
    return data_list[start_index:end_index]


# 根据len(),page和page_num返回总页数
def inquire_total_page(total_num, page_num):
    if total_num % page_num:
        len_now = ((total_num-total_num % page_num) / page_num) + 1
    else:
        len_now = (total_num / page_num)
    return int(len_now)


# 根据object_id,object_type来获取项目标题
def search_object_title(object_id, object_type):
    if object_type == "question":
        que = Questions.query.filter_by(question_id=object_id).first()
        return que.question_title
    elif object_type == "special":
        sp = Special.query.filter_by(special_id=object_id).first()
        return sp.special_title
    elif object_type == "spdy":
        spdy = SpDy.query.filter_by(spdy_id=object_id).first()
        return spdy.spdy_title
    elif object_type == "bookshelf":
        bsf = Bookshelf.query.filter_by(bookshelf_id=object_id).first()
        return bsf.bookshelf_title
    elif object_type == "dynamic":
        dy = Dynamic.query.filter_by(dynamic_id=object_id).first()
        return dy.dynamic_title
    else:
        return False


# 查询项目的标签包
def search_object_tag(object_id, object_type):
    tag_ids = list(set(TagRelation.query.with_entities(TagRelation.tagrelation_tag_id)
                       .filter_by(tagrelation_object=object_id, tagrelation_type=object_type)
                       .all()))
    tags = Tag.query.filter(Tag.tag_id.in_(tag_ids)).all()

    # 提取查询结果中的 tag_name 并创建一个列表
    tag_names = [tag.tag_name for tag in tags]
    return tag_names


# 创建UUID（通用唯一标识符）随机命名符
def unique_filename(original_filename):
    file_extension = os.path.splitext(original_filename)[-1]
    return f"{uuid.uuid4().hex}{file_extension}"


# 创建评论区
def creat_review1(review_object_type, review_user, review_object_id, review_grade_top,
                  review_text, review_top_id, review_backer):
    review = Review(
        review_object_type=review_object_type,
        review_user=review_user,
        review_object_id=review_object_id,
        review_grade_top=review_grade_top,
        review_text=review_text,
        review_top_id=review_top_id,
        review_backer=review_backer
    )
    db.session.add(review)
    db.session.commit()
    return True


# 检验tag是否重复
def validate_tag(tag_name):
    tag = Tag.query.filter_by(tag_name=tag_name).first()
    return tag is None


# 创建Tag标签
def creat_tag(tags):
    num = len(tags)
    print(num, "--num")
    arr = []
    j = 0
    for i in range(0, num):
        if validate_tag(tags[i]):
            tag_name = tags[i]
            # print(tag_name, "--tag_name")

            tag = Tag(
                tag_name=tag_name
            )
            db.session.add(tag)
            db.session.commit()
            print("tag创建")

            arr.append({'id': tag.tag_id, 'tag_name': tag.tag_name})
        else:
            tag_id = Tag.query.filter_by(tag_name=tags[i]).first()
            arr.append({'id': tag_id.tag_id, 'tag_name': tags[i]})
        j += 1

    return arr, j


# 建立Tag关系表
def creat_tagrelation(tagrelation_object, tagrelation_type, arr, i):
    for q in range(0, i):
        tagrelation_tag_id = int(arr[q].get('id'))
        tagrelation_now = TagRelation(
            tagrelation_tag_id=tagrelation_tag_id,
            tagrelation_object=tagrelation_object,
            tagrelation_type=tagrelation_type
        )
        db.session.add(tagrelation_now)
        db.session.commit()
    return True


# 将图片存入
def creat_pic(pics, type, object_id):
    if pics is not None:
        arr = []
        j = len(pics)
        for picture_address in pics:
            picture_ob_type = type
            picture_object = int(object_id)
            picture_size = None
            picture_type = None
            pic_now = Picture(
                picture_ob_type=picture_ob_type,
                picture_address=picture_address,
                picture_object=picture_object,
                picture_size=picture_size,
                picture_type=picture_type
            )
            db.session.add(pic_now)
            db.session.commit()
            pic = Picture.query.filter_by(picture_address=picture_address).first()
            arr.append({'picture_id': pic.picture_id, 'picture_address': pic.picture_address})
            print(pic_now)
        return arr, j
    else:
        return 0


# 检验问题标题是否重复
def validate_question(question_title):
    que = Questions.query.filter_by(question_title=question_title).first()
    return que is not None


# 将文章放入书架
def movein_dynamic(bookrelation_bookshelf_id, bookrelation_dynamic_id, bookrelation_user_id):
    bra = Bookrelation(
        bookrelation_bookshelf_id=bookrelation_bookshelf_id,
        bookrelation_dynamic_id=bookrelation_dynamic_id,
        bookrelation_user_id=bookrelation_user_id
    )
    db.session.add(bra)
    db.session.commit()


# 检查该书架中是否有同一篇文章
def validate_bookshelf_dynamic(bookshelf_id, dynamic_id):
    vbd = Bookrelation.query.filter_by(bookrelation_bookshelf_id=bookshelf_id, bookrelation_dynamic_id=dynamic_id).first()
    return vbd is not None


# 检查该专栏是否存在
def validate_special(special_id):
    sp = Special.query.filter_by(special_id=special_id).first()
    return sp is not None


# 检查同一位用户是否拥有相同标题的书架
def validate_bookshelf(user_id, bookshelf_title):
    bsf = Bookshelf.query.filter_by(bookshelf_user_id=user_id, bookshelf_title=bookshelf_title).first()
    return bsf is not None


# 创建书架,并返回该书架的id
def create_bookshelf(user_id, bookshelf_title):
    shelf = Bookshelf(
        bookshelf_user_id=user_id,
        bookshelf_title=bookshelf_title
    )
    db.session.add(shelf)
    db.session.commit()
    bsf = Bookshelf.query.filter_by(bookshelf_user_id=user_id, bookshelf_title=bookshelf_title).first()
    return bsf.bookshelf_id


# 查询当前项目的评论数量
def count_review(object_id, object_type):
    count = Review.query.filter_by(review_object_id=object_id, review_object_type=object_type).count()
    return count


# 查询当前项目的点赞数量
def count_like(object_id, object_type):
    count = Like.query.filter_by(like_object=object_id, like_type=object_type).count()
    return count


# 查询当前项目的收藏数量
def count_collect(object_id, object_type):
    count = Favorite.query.filter_by(favorite_object=object_id, favorite_type=object_type).count()
    return count


# 删除某个专栏会把其下所有评论/动态清除
# 当某个区块被清除时，其下所有评论会被一同删除
# 当链接有图片的区块被删除时，其链接的图片数据也会被一同删除
# 当某个标签链接的区块为0的时候，该标签会被清除（得先拿到该标签的id）
# 思路：从下网上实现，首先开始标签清理


# 删除对象时，删除其链接的标签（清理标签关联表）,如果其标签在库中的链接数据为0条的话，将该标签移除
def delete_tagrelation(object_id, type_now):
    tra = TagRelation.query.filter_by(tagrelation_object=object_id, tagrelation_type=type_now).all()
    tag_ids = []
    if tra is None:
        return
    for relation in tra:
        tag_ids.append(relation.tagrelation_tag_id)  # 添加tag_id到列表
        db.session.delete(relation)  # 删除当前TagRelation对象
    if tag_ids is None:
        db.session.commit()
        return
    for relation in tag_ids:
        if judge_tag(relation.tagrelation_tag_id):
            tra = Tag.query.filter_by(tag_id=relation.tagrelation_tag_id).first()
            db.session.delete(tra)
    db.session.commit()

# 判断当前tag是否连接数为0
def judge_tag(tag_id):
    tra = TagRelation.query.filter_by(tagrelation_tag_id=tag_id).first()
    return tra is None


# 删除对象时，删除其链接的图片
def delete_picture(object_id, type_now):
    pic = TagRelation.query.filter_by(tagrelation_object=object_id, tagrelation_type=type_now).all()
    for relation in pic:
        db.session.delete(relation)  # 删除当前TagRelation对象
    db.session.commit()  # 提交事务，使删除操作生效


# 某个一级评论被删除时，其下二级评论也会被一同删除
def delete_small_review(review_object_id, review_object_type, review_top_id):
    dsr = Review.query.filter_by(review_object_id=review_object_id, review_object_type=review_object_type,
                                 review_top_id=review_top_id).all()
    for relation in dsr:
        db.session.delete(relation)
    db.session.commit()  # 提交事务，使删除操作生效


# 某个小区块被删除的时候，例如动态,提问；其下的评论会被一同删除
def delete_small(review_object_id, review_object_type):
    dsr = Review.query.filter_by(review_object_id=review_object_id,
                                 review_object_type=review_object_type).all()
    for relation in dsr:
        db.session.delete(relation)
    db.session.commit()  # 提交事务，使删除操作生效


# 某个大区块,例如：专栏被删除时，会清理其下专栏下的文章
def delete_big(object_type, object_id):
    if object_type == 'Special':  # 如果类型为专栏
        delbg = SpDy.query.filter_by(spdy_father=object_id).all()
        for relation in delbg:
            # 清理标签
            delete_tagrelation(relation.spdy_id, 'SpDy')
            delete_picture(relation.spdy_id, 'SpDy')
            db.session.delete(relation)
        db.session.commit()  # 提交事务，使删除操作生效


# 删除书架的时候，会清理绑定这个书架的所有文章关系，但是不删除文章
def clear_bookshelf(bookshelf_id):
    delbg = Bookrelation.query.filter_by(bookrelation_bookshelf_id=bookshelf_id).all()
    for relation in delbg:
        db.session.delete(relation)
    db.session.commit()  # 提交事务，使删除操作生效


# 删除问题的时候不止要删除其下评论，还得删除其被采纳的评论的关系表
def delete_question_relation(question_id):
    delbg = QuestionRelation.query.filter_by(querelation_object=question_id).all()
    for relation in delbg:
        db.session.delete(relation)
    db.session.commit()
